﻿//获取审批人列表
$(function () {
    var userInfo=JSON.parse(localStorage.getItem("userInfo"));
    var deptId=userInfo.childen.deptId;
    PostForm("/cwp/front/sh/makeCard!execute", "uid=m006_2&deptId="+deptId+"&roleId=53", "", getApproverList, '');
});

function getApproverList(result){
    if(result.returnCode=="0"){
        var option="";
        for(var i=0; i<result.beans.length; i++){
            option="<option value='"+result.beans[i].parkId+"'  "+(i==0?"selected":"")+">"+result.beans[i].trueName+"</option>"
            $("#auditUserId").append(option);
        }
    }
    else if(result.returnCode=="-9999"){
        tipModal('icon-cross',"获取审批人失败");
    }
    else{
        tipModal('icon-cross',result.returnMessage);
    }
}

//表单验证
$(function () {
    $.formValidator.initConfig({
        formid: "frmMain", onerror: function (msg) {return false;}, onsuccess: function () {return true;}
    });
    $("#orderName").formValidator({
        onfocus: "请输入申请标题",
        oncorrect: " "
    }).InputValidator({
        min: 2,
        max: 40,
        onempty: "请输入申请标题",
        onerror: "标题长度为2到40个字符"
    });

    //
    //$("#auditUserId").formValidator({
    //    onfocus: "请选择审批人",
    //    oncorrect: " "
    //}).InputValidator({
    //    min: 1,
    //    onempty: "请选择审批人",
    //    onerror: "请选择审批人"
    //}).DefaultPassed();

    $("#orderDescribe").formValidator({
        onfocus: "请输入申请原因",
        oncorrect: " "
    }).InputValidator({
        min: 2,
        max: 400,
        onempty: "请输入申请原因",
        onerror: "请输入申请原因"
    });
});


//确认提交
$("#btnConfirmSubmit").on("click",function(){
    if ($.formValidator.PageIsValid()) {
        if(approverBeans.length>0){
            var strApprover=JSON.stringify(approverBeans);
            $("#hidUserCard").val(strApprover);
            $("#btnConfirmSubmit").attr("disabled", true);
            PostForm("/cwp/front/sh/makeCard!execute", "uid=m001", "post", submitApply, "","frmMain");
        }
        else{
            tipModal('icon-cross','请添加开卡人信息');
        }
    }
});

//提交申请回调函数
function submitApply(result){
    if(result.returnCode=="0"){
        tipModal('icon-checkmark','提交成功');
        $("#orderName").val("");
        //$("#auditUserId").val("");
        $("#orderDescribe").val("");
        $("#tabUserTip").show();
        $("#tabUser").hide();
        $("#tabUserPagination").hide();
        $("#tabUser").hide();
        $("#tabUserPagination").html("");
        $("#tabUserTotal span").html("0");
        $(".tipArea div").attr("class","");
        approverBeans=[];
    }
    else if(result.returnCode=="-9999"){
        tipModal('icon-cross',"提交失败");
    }
    else{
        tipModal('icon-cross',result.returnMessage);
    }
    $("#btnConfirmSubmit").removeAttr("disabled");
}


//导入文件数组对象
var approverBeans = new Array();

//初始化文件上传控件
$(function() {
    $("#file_upload").uploadify({
        height        : 28,
        swf           : '../../assets/lib/uploadify/uploadify.swf',
        uploader      : '/cwp/front/sh/makeCard!execute?uid=m007_2',
        width         : 78,
        'fileTypeExts': '*.xls; *.xlsx', //文件后缀限制 默认：'*.*'
        'fileSizeLimit': '10240KB', //文件大小限制 0为无限制 默认KB
        'fileTypeDesc' : '.xls; *.xlsx文件格式',//文件类型描述
        'method': 'post', //提交方式Post 或Get 默认为Post
        'buttonText': '', //按钮文字

        'multi': false, //多文件上传
        'fileObjName': 'files[]', //设置一个名字，在服务器处理程序中根据该名字来取上传文件的数据。默认为Filedata
        'queueID': 'I am dont need',  //默认队列ID
        'removeCompleted': true, //上传成功后的文件，是否在队列中自动删除
        'overrideEvents': ['onDialogClose', 'onSelectError','onUploadStart', 'onUploadSuccess', 'onUploadError'],//重写事件
        //返回一个错误，选择文件的时候触发          
        'onSelectError': function (file, errorCode, errorMsg) {
            var msgText = "";
            switch (errorCode) {
                case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
                    //this.queueData.errorMsg = "每次最多上传 " + this.settings.queueSizeLimit + "个文件";
                    msgText += "每次最多上传 " + this.settings.queueSizeLimit + "个文件";
                    break;
                case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
                    msgText += "文件大小超过限制" + this.settings.fileSizeLimit + "";
                    break;
                case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
                    msgText += "文件大小为0";
                    break;
                case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
                    msgText += "文件格式不正确，仅限 " + this.settings.fileTypeExts;
                    break;
                default:
                    msgText += "错误代码：" + errorCode + "\n" + errorMsg;
            }
            tipModal('icon-cross',msgText);
        },
        // 文件开始上传时回调函数
        'onUploadStart': function (file) {
            //显示上传状态
            $("#uploadTip").text("正在上传...").attr("class","t-loading-cmcc");
        },

        //// 当文件上传中的回调方法
        //'onUploadProgress': function (file, bytesUploaded, bytesTotal, totalBytesUploaded, totalBytesTotal) {
        ////    // 设置进度条级显示的百分比
        //},

        //检测FLASH失败调用
        'onFallback': function () {
            alert("您未安装FLASH控件，无法上传图片！请安装FLASH控件后再试。");
        },

        //文件上传成功后的回掉方法
        'onUploadSuccess': function (file, data, response) {
            var data=JSON.parse(data)
            if(data.returnCode == '0'){
                //excel列表数据
                approverBeans=data.beans;
                if(approverBeans.length>0){
                    initPagination(approverBeans.length);
                    tipModal('icon-checkmark','导入完成');
                }
            }
            else if(data.returnCode == '-9999'){
                tipModal('icon-cross','导入失败');
            }
            else{
                tipModal('icon-cross',data.returnMessage);
            }
            $("#uploadTip").text("批量导入").attr("class","t-btn t-btn-blue");
        },

        //文件上传出错时触发，参数由服务端程序返回。
        'onUploadError': function (file, errorCode, errorMsg, errorString) {
            tipModal('icon-cross',"上传出现异常，请重新上传");
        }
    });
});


//当前页，加载容器
function paginationCallback(page_index){
    searchUserList(page_index);
    pageCount=page_index;
    return false;
}

var pageIndex=0;
var pageSize=8;
var pageCount=0;
//渲染导入申请人数据
function searchUserList(pageCount) {
    var data=approverBeans.slice(pageCount+pageCount*(pageSize-1),pageSize+pageCount*pageSize);
    if(data.length>0){
        $("#tabUserTip").hide();
        $("#tabUser").show();
        $("#tabUserPagination").show();
        //获取搜索先关条件 默认搜索数据为空
        template.helper('genderFormat', function(inp) {
            if(inp == "0") {
                return '男';
            } else if(inp == "1") {
                return '女';
            }
        });
        var outHtml = template("approverListTmpl", data);
        $("#tabUser tbody").html(outHtml);

    }
    else{
        $("#tabUserTip").show();
        $("#tabUser").hide();
        $("#tabUserPagination").hide();
    }


}


//分页
function initPagination(pageTotal){
    $("#tabUserTotal span").text(pageTotal);
    $("#tabUserPagination").pagination(pageTotal, {
        num_edge_entries: 1, //边缘页数
        num_display_entries: 4, //主体页数
        callback: paginationCallback,
        items_per_page: pageSize, //每页显示1项
        current_page: pageIndex,
        prev_text: "上一页",
        next_text: "下一页",
        link_to:"javascript:void(0)"
    });
}


//---------------------------新增人员-----------------------------------
function showApproverModal(){
    $("#modalCardholder").modal({//启用modal ID
        keyboard: true,
        backdrop: 'static'
    }).on('show.bs.modal');
}

//添加开卡人
$("#btnAdd").on("click",function(){
    $("#modal-title-approver").text("新增开卡人员");
    $("#frmMainApprover input").val("");
    $("#frmMainApprover .tipArea div").html("").attr("class","");
    $("#boy").val("0");
    $("#girl").val("1");
    showApproverModal();
});

$(function(){
    formValidator();
});

function formValidator(){
    $.formValidator.initConfig({
        validatorGroup:"2",
        formid: "frmMainApprover", onerror: function (msg) {
            return false;
        }, onsuccess: function () {
            return true;
        }
    });

    $("#trueName").formValidator({
        validatorGroup:"2",
        onfocus: "请输入姓名",
        oncorrect: " "
    }).InputValidator({
        min: 4,
        max: 20,
        onempty: "请输入姓名",
        onerror: "姓名长度只能在4-8位字符之间"
    }).RegexValidator({
        regexp: "realname",
        datatype: "enum",
        onerror: "姓名只能为汉字"
    });

    $("#phone").formValidator({
        validatorGroup:"2",
        onfocus: "请输入手机号",
        oncorrect: " "
    }).InputValidator({
        min: 11,
        max: 11,
        onempty: "请输入手机号",
        onerror: "手机号码长度为11位"
    }).RegexValidator({
        regexp: "mobile",
        datatype: "enum",
        onerror: "手机号码格式无效"
    }).FunctionValidator({
        fun:function(val,elem) {
            var oldPhone = $("#oldPhone").val();
            if (oldPhone == val) {
                return true;
            }

            if (approverBeans.length > 0) {
                //本地数据验证
                for (var i = 0; i < approverBeans.length; i++) {
                    if (approverBeans[i].phone == val) {
                        return "该手机号码已添加";
                    }
                }
            }

            var htmlObj = $.ajax({
                type: "post",
                url: "/cwp/front/sh/makeCard!execute",
                beforeSend:function(requests){
                    requests.setRequestHeader("platform", "pc");
                },
                async: false,
                dataType: "json",
                data: {
                    uid: "m009_2",
                    userId: localStorage.getItem("parkId"),
                    phone: $("#phone").val()
                }
            });
            var result = JSON.parse(htmlObj.responseText);
            if (result.returnCode == "0") {
                return true;
            } else {
                return "该手机号码已添加";
            }



        }
    });

    $("#emno").formValidator({
        validatorGroup:"2",
        onfocus: "请输入员工编号",
        oncorrect: " "
    }).InputValidator({
        min: 4,
        max: 20,
        onempty: "请输入员工编号",
        onerror: "员工编号长度为4-20个字符"
    }).FunctionValidator({
        fun:function(val,elem){
            var oldEmno=$("#oldEmno").val();
            if (val == oldEmno) {
                return true;
            }

            if(approverBeans.length>0){
                //本地数据验证
                for(var i=0; i<approverBeans.length; i++){
                    if(approverBeans[i].standby==val){
                        if (val != oldEmno){
                            return "该员工编号已申请过";
                        }

                    }
                }
            }

            //数据库数据验证
            var htmlObj = $.ajax({
                type: "post",
                url: "/cwp/front/sh/makeCard!execute",
                beforeSend:function(requests){
                    requests.setRequestHeader("platform", "pc");
                },
                async: false,
                dataType: "json",
                data: {
                    uid: "m009_2",
                    userId: localStorage.getItem("parkId"),
                    emno: $("#emno").val()
                }
            });
            var result = JSON.parse(htmlObj.responseText);
            if (result.returnCode == "0") {
                return true;
            } else {
                return "该员工编号已申请过";
            }
        }

    });


    $("#idno").formValidator({
        validatorGroup:"2",
        onshow:"请输入身份证号",
        onfocus:"请输入身份证号",
        oncorrect:"&nbsp;"
    }).InputValidator({
        min: 15,
        max: 18,
        onempty: "请输入身份证号",
        onerror: "身份证号的长度为15或18位"
    }).RegexValidator({
        regexp: "idcard",
        datatype: "enum",
        onerror: "请输入正确格式的身份证号"
    }).FunctionValidator({
        fun:function(val,elem){
            var oldIdno=$("#oldIdno").val();
            //数据库数据验证
            if (val == oldIdno) {
                return true;
            }
            if(approverBeans.length>0){
                for(var i=0; i<approverBeans.length; i++){
                    if(approverBeans[i].idCardNo==val){
                        if (val != oldIdno) {
                            return "该身份证号已添加";
                        }
                    }
                }
            }

            var htmlObj = $.ajax({
                type: "post",
                url: "/cwp/front/sh/makeCard!execute",
                beforeSend : function(requests) {
                    requests.setRequestHeader("platform", "pc");
                },
                async: false,
                dataType: "json",
                data: {
                    uid: "m009_2",
                    userId: localStorage.getItem("parkId"),
                    idno: $("#idno").val()
                }
            });
            var result = JSON.parse(htmlObj.responseText);
            if (result.returnCode == "0") {
                return true;
            } else {
                return result.returnMessage;
            }

        }
    });
}



//提交申请人
$("#btnSave").on("click",function(){
    if ($.formValidator.PageIsValid(2)){
        //当前编辑索引
        var index=$("#hidIndex").val();
        //索引为空为新增，反之为编辑
        if(index==""){
            var obj=new initApprover();
            approverBeans.unshift(obj);
            initPagination(approverBeans.length);
        }else{
            approverBeans[index].userName=$("#trueName").val();
            approverBeans[index].sex=$("[name='sex']:checked").val();
            approverBeans[index].phone=$("#phone").val();
            approverBeans[index].standby=$("#emno").val();
            approverBeans[index].idCardNo=$("#idno").val();
            //获取当前页
            paginationCallback(pageCount);
        }
        $('#modalCardholder').modal('hide');
    }
});

//初始化申请人对象
function initApprover(){
    this.userName=$("#trueName").val();
    this.sex=$("input[name='sex']:checked").val();
    this.phone=$("#phone").val();
    this.standby=$("#emno").val();
    this.idCardNo=$("#idno").val();
    this.cardNo="";
    this.cardStatus="";
    this.delFlag="";
    this.id="";
    this.orderNum="";
    return this;
}

//删除申请人
$(document).on("click","#btnDelete",function(){
    var phone=$(this).attr("data-phone");
    for(var i=0; i<approverBeans.length; i++){
        if(approverBeans[i].phone==phone){
            approverBeans.splice(i,1);
            initPagination(approverBeans.length);
        }
    }
});

//编辑申请人
$(document).on("click","#btnEdit",function(){
    var phone=$(this).attr("data-phone");
    for(var i=0; i<approverBeans.length; i++){
        if(approverBeans[i].phone==phone){
            $("#modal-title-approver").text("编辑开卡人员");
            $("#trueName").val(approverBeans[i].userName);
            if(approverBeans[i].sex=="0"){
                $("#boy")[0].checked=true;
            }
            else{
                $("#girl")[0].checked=true;
            }
            $("#phone").val(approverBeans[i].phone);
            $("#emno").val(approverBeans[i].standby);
            $("#idno").val(approverBeans[i].idCardNo);
            //隐藏域保存旧电话、旧员工编号、旧身份证
            $("#oldPhone").val(approverBeans[i].phone);
            $("#oldEmloyeeNo").val(approverBeans[i].standby);
            $("#oldEmno").val(approverBeans[i].standby);
            $("#oldIdno").val(approverBeans[i].idCardNo);
            $("#oldCardId").val(approverBeans[i].idCardNo);
            $("#hidIndex").val(i);
            showApproverModal();
        }
    }
});